package jeecg.business.thread.task.impl;

import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import jeecg.business.entity.enter.EnterEntity;
import jeecg.business.entity.keyinfo.KeyinfoEntity;
import jeecg.business.entity.keyword.KeywordEntity;
import jeecg.business.entity.log.CollLogEntity;
import jeecg.business.entity.site.SiteEntity;
import jeecg.business.thread.HtmlFetchManage;
import jeecg.business.vo.ProxyIpVo;

import org.apache.commons.lang.math.RandomUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.clean.CommonHtmlCleanUtil;
import org.jeecgframework.core.util.clean.bean.FetchListInfo;
import org.jeecgframework.core.util.clean.bean.HtmlParseResult;
import org.jeecgframework.core.util.clean.bean.InfoParam;
import org.jeecgframework.core.util.http.HttpClientUtil;

/**
 * 
 * <p>
 * 标题: 微信
 * </p>
 * <p>
 * 描述: // TODO
 * </p>
 * 
 * @author LinYingPiaoJian(Q:71426052)
 * @version // TODO
 * @since 2015-6-6 下午10:05:02
 */
public class WeixinExecTask extends CommonExecTask{
	
	String ip;
	
	int port;
	
	
	public WeixinExecTask(EnterEntity enter , KeywordEntity keyword, SiteEntity site ) {
		super(enter , keyword, site);
	}
	
	void getIpAndPort(){
		ProxyIpVo ips;
		try {
			ips = HtmlFetchManage.getIpCanUsed();
			String []ipport = ips.getIpandport().split(":");
			ip = ipport[0];
			port = Integer.parseInt(ipport[1]);
		} catch (Exception e) {
			
		}
	}
	
	public void setCookies(){
		String baseurl = getFetchHtml();
		String html = null;
		

		if(HtmlFetchManage.proxyIsUse == 1){
			do{
				getIpAndPort();
				if((port+"").startsWith("80") || (port+"").startsWith("90")){
					html = HttpClientUtil.getSourceFromUrl(baseurl, site.getWyzfj(), null , ip , port);
				}
				System.out.println("切换一个ip，打印避免死循环");
			}while(StringUtil.isEmpty(html) || !html.contains("搜狗"));
			System.out.println("可用IP："+ip+"-"+port);
		}else{
			html = HttpClientUtil.getSourceFromUrl(baseurl, site.getWyzfj(), null);
		}
		
		
	}
	
	
	public void run(){
//		if(StringUtil.isEmpty(ip)) return;
		CollLogEntity log = null;
		log = saveLog();
		try{
			System.out.println("exec weixin task......");
			String basehref = site.getZddz();
			String word = URLEncoder.encode(keyword.getKeyword(),site.getWyzfj());
			basehref = basehref.replace(KEYWORD_FLAG, word);
			String paramBaseHref = basehref;
			setCookies();
			do{
				current++;
				System.out.println(keyword.getKeyword()+"-----"+site.getMc()+"-----第"+current+"页"+"-----"+basehref);
//				cookies = null;
				HttpClientUtil.cookiesMap.remove(ip+":"+port);
				if(StringUtil.isNotEmpty(basehref)){
					FetchListInfo info = null;
					int time = 0;
					while(time <= 10 && (info == null || info.getHrefList() == null || info.getHrefList().size() == 0)){
						info = CommonHtmlCleanUtil.getListUrl4Proxy(basehref, site , null , ip , port);
//						System.out.println("time-"+time+":"+info);
						if(info == null || info.getHrefList() == null || info.getHrefList().size() == 0) setCookies();
						time ++;
					}
					cookies = HttpClientUtil.cookiesMap.get(ip+":"+port);
					if("param".equals(site.getXyyhqfs())){
						if(!basehref.contains("{page}")) basehref = paramBaseHref + "&"+site.getLbxyy()+"={page}";
						basehref = basehref.replace("{page}", (current+1)+"");
						info.setNextPage(basehref);
					}else{
						basehref = info.getNextPage();
					}
					if(StringUtil.isNotEmpty(basehref) && !basehref.startsWith("http:"))
						basehref = "http://weixin.sogou.com/weixin"+basehref;
					
					List<String> urlList = info.getHrefList();
					if(urlList!=null && urlList.size()>0){
						HtmlParseResult result = null;
						KeyinfoEntity keyinfo = null;
						for(String url : urlList){
							url = url.replace("&amp;", "&");
							/**
							 * 单个错误时跳过
							 */
							try{
								InfoParam infoparam = new InfoParam();
								infoparam.setListInfo(info);
								//获取下location
								if(!url.startsWith("http")) url = site.getGdz() + url;
//								String location = HttpClientUtil.getCookiesValue(url, site.getNyzfj() , cookies, ip, port, "Location");
//								System.out.println("location:"+location);
//								if(StringUtil.isNotEmpty(location))
//									url = location;
								result = CommonHtmlCleanUtil.getInfo4proxy(url, site, keyword.getKeyword() , cookies , infoparam , ip , port);
								keyinfo = new KeyinfoEntity(result);
								keyinfo.setQyid(enter.getId());
								if(filter(enter, keyinfo , keyword))		//过滤
									keyinfoService.saveKeyinfo(keyinfo);
							}catch(Exception e1){
								e1.printStackTrace();
							}							
						}
					}else{
						return;
					}
				}
				if("wx".equals(site.getJclx())){
					Thread.sleep((5+RandomUtils.nextInt(10))*1000);
				}
			}while(current <= maxpage);
//			log = collLogService.get(CollLogEntity.class, log.getId());
		}catch(Exception e){
			e.printStackTrace();
//			log.setSfcg("2");
//			log.setCwxx(e.getMessage());
		}finally{
			log = collLogService.get(CollLogEntity.class, log.getId());
			log.setJssj(new Date());
			collLogService.updateEntitie(log);
			System.out.println("end....");
		}		
	}

}
